<template>
  <div class="chat-container">
    <div class="message-list" ref="messageList">
      <div v-for="(message, index) in messages" :key="index" class="message-item" :class="{ 'message-self': message.isSelf }">
        <div v-if="!message.isSelf" class="avatar">
          <el-avatar :size="40" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
        </div>
        <div class="message-content">
          <div v-if="!message.isSelf" class="message-sender">{{ message.sender }}AI助手</div>
          <div class="message-content-wrapper">
            <div class="message-text">{{ message.text }}</div>
          </div>
          <div class="message-time">{{ message.time }}</div>
        </div>
      </div>
    </div>
    <div class="chat-input">

      <div class="input-area">
        <el-input
          v-model="inputMessage"
          type="textarea"
        :autosize="{ minRows: 1, maxRows: 7 }"
        placeholder="输入你的问题"
        class="wide-input"
        resize="none"
        />
      
       <div class="action-bar">
        <el-button 
          type="primary" 
          @click="sendMessage"
          :icon="ArrowRight"
          circle
          class="send-button"
        />
      </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { Picture, Files, ArrowRight } from '@element-plus/icons-vue'
// import * as echarts from 'echarts'

// 对话框相关状态
const dialogVisible = ref(false)
const currentRainfallData = ref(null)
const flowDialogVisible = ref(false)
const flowChartData = ref(null)
const flowChartInstance = ref(null)


const socket = ref(null)
const isConnecting = ref(false)
const reconnectAttempts = ref(0)
const maxReconnectAttempts = 5
const reconnectDelay = 3000

// 保存当前对话到历史记录
const saveToHistory = () => {
  const savedHistory = localStorage.getItem('chatHistory') || '[]'
  const history = JSON.parse(savedHistory)
  history.push({
    startTime: new Date().getTime(),
    messages: messages.value
  })
  localStorage.setItem('chatHistory', JSON.stringify(history))
}

// 连接 WebSocket
const connectWebSocket = () => {
  if (isConnecting.value || reconnectAttempts.value >= maxReconnectAttempts) return

  isConnecting.value = true
  socket.value = new WebSocket('ws://10.10.10.125:8002/ws/chat')

  socket.value.onopen = () => {
    console.log('Connected to server')
    isConnecting.value = false
    reconnectAttempts.value = 0
  }

  socket.value.onerror = (error) => {
    console.error('WebSocket error:', error)
    isConnecting.value = false
  }

  socket.value.onclose = () => {
    console.log('WebSocket connection closed')
    isConnecting.value = false

    if (reconnectAttempts.value < maxReconnectAttempts) {
      reconnectAttempts.value++
      console.log(`Attempting to reconnect (${reconnectAttempts.value}/${maxReconnectAttempts})...`)
      setTimeout(connectWebSocket, reconnectDelay)
    } else {
      console.log('Max reconnection attempts reached')
      messages.value.push({
        sender: 'System',
        avatar: '',
        text: '连接已断开，请刷新页面重试',
        time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
        isSelf: false
      })
    }
  }

  socket.value.onmessage = (event) => {
    let data
    try {
      data = JSON.parse(event.data)
    } catch (error) {
      console.error('解析消息失败:', error)
      return
    }

    if (!data) {
      console.error('接收到无效的消息数据')
      return
    }

    // 处理流式响应
    if (data.type === 'chunk' || data.type === 'done' || data.type === 'error') {
      // 检查是否包含降雨数据查询关键词
      const isRainfallQuery = inputMessage.value.includes('历史降雨') || inputMessage.value.includes('降雨数据')
      const lastMessage = messages.value[messages.value.length - 1]
      if (!lastMessage || lastMessage.isSelf) {
        // 创建新的系统消息
        const messageData = {
          sender: 'Hydro',
          avatar: '',
          text: data.type === 'error' ? `错误：${data.content}` : (data.content || ''),
          time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
          isSelf: false,
          showRainfallButton: isRainfallQuery,
          query: inputMessage.value
        }
        messages.value.push(messageData)
        // 仅在完成或错误时保存消息
        if (data.type === 'done' || data.type === 'error') {
          saveMessages()
        }chufade
      } else {
        // 更新最后一条系统消息
        if (data.type === 'chunk') {
          lastMessage.text += data.content
        } else if (data.type === 'error') {
          lastMessage.text = `错误：${data.content}`
          saveMessages()
        }
      }
    } else {
      // 处理其他类型的消息
      const messageData = {
        sender: 'Hydro',
        avatar: data.avatar || '',
        text: (data.message || data.text || '无效的消息内容').toString(),
        time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
        isSelf: false
      }
      messages.value.push(messageData)
      saveMessages()
    }

    // 使用 nextTick 确保在 DOM 更新后滚动
    nextTick(() => {
      if (messageList.value) {
        messageList.value.scrollTop = messageList.value.scrollHeight
      }
    })
  }
}

// 保存当前对话到历史记录
const saveMessages = () => {
  saveToHistory()
}

const route = useRoute()

// 监听连接事件
onMounted(() => {
  connectWebSocket()
  // 确保在组件挂载后滚动到底部
  nextTick(() => {
    if (messageList.value) {
      messageList.value.scrollTop = messageList.value.scrollHeight
    }
    // 检查是否有从Home页面传递过来的消息
    const query = route.query.q
    if (query) {
      inputMessage.value = query
      // 等待WebSocket连接建立后再发送消息
      const waitForConnection = () => {
        if (socket.value && socket.value.readyState === WebSocket.OPEN) {
          sendMessage()
        } else if (reconnectAttempts.value < maxReconnectAttempts) {
          setTimeout(waitForConnection, 500)
        }
      }
      waitForConnection()
    }
  })
})

// 组件卸载时断开连接
onUnmounted(() => {
  if (socket.value) {
    socket.value.close()
  }
})

// 消息列表
const messages = ref([
  {
    sender: 'Hydro',
    avatar: '',
    text: '你好，请问有什么可以帮助你的吗？',
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    isSelf: false
  }
])

// 输入框消息
const inputMessage = ref('')

// 消息列表容器引用
const messageList = ref(null)

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) return

  const messageData = {
    sender: '我',
    avatar: '',
    text: inputMessage.value,
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    isSelf: true
  }

  messages.value.push(messageData)
  const currentQuery = inputMessage.value
  inputMessage.value = ''

  // 检查是否包含降雨数据查询关键词
  const isRainfallQuery = currentQuery.includes('历史降雨') || currentQuery.includes('降雨数据')

  // 如果是降雨数据查询，先获取历史降雨数据
  if (isRainfallQuery) {
    try {
      const response = await fetch(`http://10.10.10.125:8002/api/history_rainfall?query=${encodeURIComponent(currentQuery)}`, {
        method: 'POST'
      })
      const data = await response.json()
      currentRainfallData.value = data
      dialogVisible.value = true
    } catch (error) {
      console.error('获取历史降雨数据失败:', error)
      messages.value.push({
        sender: 'Hydro',
        avatar: '',
        text: '获取历史降雨数据失败，请稍后重试',
        time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
        isSelf: false
      })
    }
  }

  // 发送消息到服务器获取回答
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    socket.value.send(JSON.stringify({
      query: currentQuery
    }))
  }

  // 滚动到底部
  
}

</script>

<style scoped>
/* 保持原有的样式不变 */
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  padding-bottom: 20px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  width: 100%;
  max-width: 1000px;
  margin-bottom: 20px;
}

.message-list::-webkit-scrollbar {
  width: 8px;
}

.message-list::-webkit-scrollbar-track {
  background: transparent;
}

.message-list::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background-color: rgba(248, 250, 255, 0.5);
}
.message-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  gap: 8px;
}

.message-item.message-self {
  justify-content: flex-end;
}

.message-item:not(.message-self) {
  justify-content: flex-start;
}

.message-content {
  max-width: 60%;
}

.avatar {
  flex-shrink: 0;
}

.message-sender {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.message-content-wrapper {
  background-color: #f5f7fa;
  padding: 12px 16px;
  border-radius: 4px;
  margin-bottom: 4px;
}

.message-text {
  color: black;
  line-height: 1.5;
  white-space: pre-wrap;
}

.message-self .message-content-wrapper {
  background-color: #e6f7ff;
}

.message-time {
  font-size: 12px;
  color: #999;
  text-align: right;
}

.chat-input {
  width: 100%;
  max-width: 1000px;
  display: flex;
  justify-content: center;
}


.input-area {
  width: 100%;
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.wide-input :deep(.el-textarea__inner) {
  width: 100%;
  font-size: 16px;
  padding: 16px 20px;
  border: none;
  outline: none;
  color: #333;
  resize: none;
  line-height: 1.5;
  min-height: 60px;
  background: transparent;
  box-shadow: none;
}

/* 操作栏样式 */
.action-bar {
  display: flex;
  justify-content: flex-end;
  padding: 8px 16px;
  background: #fff;
}

.send-button {
  display: flex;
  justify-content: flex-end;
  padding: 8px 16px;
  background: #fff;
}

.send-button {
  width: 40px;
  height: 40px;
  min-width: 40px;
  padding: 0;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 50%;
}

.send-button.is-circle {
  border-radius: 50%;
  padding: 0;
}

.send-button:hover {
  background-color: #66b1ff;
}
</style>

